// axios二次封装
import axios from 'axios'
import { useUserStore } from '@/stores/user'

const http = axios.create({
	// 基础路径
	baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
	// 超时时间
	timeout: 5000,
})

// 请求拦截器
http.interceptors.request.use(
	config => {
		const userStore = useUserStore()
		const token = userStore.userInfo.token
		if (token) {
			config.headers.Authorization = `Bearer ${token}`
		}
		return config
	},
	error => {
		return Promise.reject(error)
	},
)

// 响应拦截器
http.interceptors.response.use(
	response => {
		return response.data
	},
	error => {
    if (error.response?.status === 401) {
			const userStore = useUserStore()
			userStore.clearUserInfo()
		}
		return Promise.reject(error)
	},
)

export default http
